-- UISkyResource
-- Create by huanghr
-- 天空之城的物资仓库

require "game/ui/form/sky_city/UICaptainDiary";

-- UISkyResource继承自Layer
UISkyResource = class("UISkyResource", function()
    return cc.Layer:create();
end);

function UISkyResource.create()
    return UISkyResource.new();
end

-- 最大行数
local MAX_GRID_ROW  = 4;
local PAGE_COLUMN   = 4;
local airShipList   = {};

-- 标签对应的显示类型
local tabType  = { "use", "resource", "robot", "stone"};

-- 符石排序顺序
local stoneSortOrder = {["revenge"] = 1, ["explore"] = 2, ["plunder"] = 3};

-- 内部函数声明

-- 构造函数
function UISkyResource:ctor()
    -- 初始化
    self:setName("UISkyResource");
    local node = cc.CSLoader:createNode("layout/sky_city/SkyCityTeam.csb");
    self:addChild(node);
    self.node = node;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);
    self.pageIndex = 1;

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 调整下标题背景图片资源
    local bgTypeImg1 = findChildByName(self.node, "CT/template/bg_type");
    local bgTypeImg2 = findChildByName(self.node, "CT/template/bg_type2");
    bgTypeImg2:setVisible(true);
    bgTypeImg1:loadTexture(getTitleBgIconPath("airship"));
    bgTypeImg2:loadTexture(getTitleBgIconPath("airship"));

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化仓库物品
    self:initData();

    -- 初始化格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 初始化标签页
    self:initTabs();

    -- 适配
    self:resize();
end

-- 适配
function UISkyResource:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化标签页
function UISkyResource:initTabs()
    local tabNode = findChildByName(self.node, "CT/tab");
    tabNode:setVisible(true);

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    local tabItem = cc.CSLoader:createNode("layout/tab/tab.csb");
    local widget = replaceNodeWithWidget(tabItem);
    for i = 1, #tabType do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 98 + 70;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");
        tabImage.groupNum = tabType[i];

        tabIcon:setVisible(false);
        tabText:setPositionX(tabText:getPositionX() + 1);
        TextStyleM.setTextStyle(tabText, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        tabText:setString(self:getTabText()[i]);

        -- 置灰颜色
        local blendColor = TextStyleM.TEXT_COLOR_BLEND;
        local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

        if i == 1 then
            -- 当前标签页高亮
            tabLight:setVisible(true);
            self.pageIndex = i;
            tabImage:loadTexture(getTabIconPath("red"));
        else
            tabLight:setVisible(false);
            tabImage:setColor(blendColor);
            tabText:setColor(blendColor);
            tabImage:loadTexture(getTabIconPath("blue"));
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 获取标签文本
function UISkyResource:getTabText()
    local tabTextArray  = {
        getLocStr("tab_text_use"),
        getLocStr("tab_text_resource"),
        getLocStr("tab_text_robot"),
        getLocStr("tab_text_stone"),
    };
    return tabTextArray;
end

-- 页签动画效果
function UISkyResource:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.2 * (i - 1));
        local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 点击标签页
function UISkyResource:registerTabTouchEvent(node)
    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local tabImage = node:getChildByName("tab");
    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除上一个高亮
            local tabNode = findChildByName(self.node, "CT/tab");
            for _, child in pairs(tabNode.rows) do
                if child.index == self.pageIndex then
                    -- 去除高亮
                    local tabLight = findChildByName(child, "light");
                    local tabImage = findChildByName(child, "tab");
                    local tabText  = findChildByName(child, "text");
                    tabLight:setVisible(false);
                    tabImage:setColor(blendColor);
                    tabText:setColor(blendColor);
                end
            end
            -- 设置当前高亮
            local tabLight = findChildByName(node, "light");
            local tabImage = findChildByName(node, "tab");
            local tabText  = findChildByName(node, "text");
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabText:setColor(normalColor);
            self.pageIndex = node.index;

            self:initData();
            -- 初始化格子
            self:initGrids(node)
            -- 重绘界面
            self:redraw();
        end
    end
    tabImage:addTouchEventListener(onClick);
end

-- 符石排序
local function sortStoneItem(item1, item2)
    local classId1 = item1.class_id;
    local classId2 = item2.class_id;

    local style1 = SkyStoneM.query(classId1, "style");
    local style2 = SkyStoneM.query(classId2, "style");

    local order1 = tonumber(stoneSortOrder[style1]);
    local order2 = tonumber(stoneSortOrder[style2]);

    if order1 < order2 then
        return true;
    elseif order1 > order2 then
        return false;
    end

    local rank1 = ItemM.query(classId1, "rank");
    local rank2 = ItemM.query(classId2, "rank");

    if rank1 > rank2 then
        return true;
    elseif rank1 < rank2 then
        return false;
    end

    return classId1 < classId2;
end

-- 排序
local function sortItem(item1, item2)
    local pos1 = item1.pos;
    local pos2 = item2.pos;
    return pos1 < pos2;
end

-- 机器人按星级由高到低排序
local function sortRobotItem(item1, item2)
    local rank1 = item1.rank;
    local rank2 = item2.rank;

    return rank1 > rank2;
end

-- 初始化飞船列表数据
function UISkyResource:initData()
    self.data = {};

    local pageName = tabType[self.pageIndex];

    -- 获得所有的物资的编号
    self.data = SkyResourceM.getResourcesByPage(pageName);

    if tabType[self.pageIndex] == "robot" then
        -- 机器人分页要特殊处理，因为机器人不是道具
        self.data = {};
        local robotList = table.keys(SkyRobotM.getAllRobots());

        for _, robotId in ipairs(robotList) do
            local robotInfo = table.deepcopy(SkyRobotM.query(robotId));
            local fightingInfo = SkyRobotM.getRobotInfo(robotId);

            robotInfo.fighting = fightingInfo.fighting;
            robotInfo.total = fightingInfo.total;
            robotInfo.amount = robotInfo.total;
            robotInfo.alias = "robot";

            -- 机器人数量必须大于0
            if robotInfo.amount > 0 then
                table.insert(self.data, robotInfo);
            end
        end
    end

    if tabType[self.pageIndex] == "stone" then
        table.sort(self.data, sortStoneItem);
    elseif "robot" == tabType[self.pageIndex] then
        table.sort(self.data, sortRobotItem);
    else
        table.sort(self.data, sortItem);
    end
end

-- 初始化格子
function UISkyResource:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 1;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 13;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 总数
    local totalCount = #self.data;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyStoreItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);
    end
end

-- 显示英雄选择界面
function UISkyResource:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    titleLabel:setString(getLocStr("sky_resource_store"));
    TextStyleM.setTitleStyle(titleLabel);

    local totalGridCount = #self.data;
    cclog("总数".. totalGridCount .. "\n");

    if not self.data or totalGridCount == 0 then
        cclog("收集物品信息失败");
        return;
    end

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, self.data[i]);
        end
    end
end

--  初始化格子信息
function UISkyResource:initGridInfo(grid, info)
    -- 物品的icon
    local bg = findChildByName(grid, "bg");
    local iconImg = findChildByName(grid, "icon");
    local buyImg = findChildByName(grid, "buy");
    local starNode = findChildByName(grid, "stars");

    iconImg:setVisible(true);

    if info["alias"] == "robot" then
        iconImg:loadTexture(getRobotIconPath(info.icon));
        bg:loadTexture(getFrameBgIconPath("airship_skill"));
    else
        iconImg:loadTexture(getItemIconPath(info.icon));
        bg:loadTexture(getFrameBgIconPath("normal"));
    end
    buyImg:setVisible(false);
    buyImg:removeAllChildren();

    if info["alias"] == "robot" or info["alias"] == "device_material" or
        info["alias"] == "energy_nuclei" or string.find(info.alias, "stone") ~= nil then
        starNode:setVisible(true);
        starNode:removeAllChildren();

        local lightStarPath = "images/ui/symbol/star_little.png";
        local rankLayer = createStarLayer(info["rank"], lightStarPath, "center", -0.25);
        starNode:addChild(rankLayer);
    else
        starNode:setVisible(false);
    end

    -- 物品的数量
    if info.amount > 0 then
        -- 数字转换
        local itemNum = tonumber(info.amount);
        local numStr = changeNumType(itemNum);

        local numLabel = findChildByName(grid, "num_label");
        numLabel:setVisible(true);
        TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);

        numLabel:setString(numStr);

        bg:setOpacity(255);
        iconImg:setOpacity(255);
    else
        -- 设置透明度
        bg:setOpacity(150);
        iconImg:setOpacity(150);

        if info["alias"] == "energy" then
            -- 如果是没有电池包，那么显示钻石购买图标
            buyImg:setVisible(true);

            playBubbleAnima(buyImg, false, 0.6);
        end
    end

    -- 注册点击事件
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            if info["alias"] == "robot" then
                -- 机器人
                self:showItemInfo(info.id, "robot");
            elseif string.find(info.alias, "stone") ~= nil then
                self:showItemInfo(info.class_id, "stone");
            elseif info.can_use == 1 then
                self:showItemInfo(info.class_id, "resource");
            elseif info.alias == "captain_dairy" then
                -- 舰长的日记
                UIMgr.getCurrentScene():removeFormByName("UICaptainDiary");
                local uiForm = UICaptainDiary.create();
                UIMgr.getCurrentScene():addForm(uiForm);
                AudioM.playFx("ui_open1");
            else
                -- 显示道具详细信息
                closeFormByName("UIItemDesc");
                local uiItemDesc = UIItemDesc.create(info.class_id);
                UIMgr:getCurrentScene():addForm(uiItemDesc);
                AudioM.playFx("button_spell");
            end
        end
    end
    bg:addTouchEventListener(onClick);
end

-- 打开详情界面
function UISkyResource:showItemInfo(classId, type)
    -- 打开物品详情界面
    closeFormByName("UISkyStoreItem");
    require "game/ui/form/sky_city/UISkyStoreItem"
    local uiForm = UISkyStoreItem.create(classId, type);
    UIMgr.getCurrentScene():addForm(uiForm);
    AudioM.playFx("button_spell");
end

-- 注册事件处理回调函数
function UISkyResource:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyResource");
        elseif eventType == "enter" then

        end
    end);

    -- 状态刷新
    EventMgr.register("UISkyResource", event.USE_SKY_CITY_RESOURSE, function(args)
        self:refreshItem();
    end);

    -- 购买商品事件回调
    EventMgr.register("UISkyResource", event.BUY_SKY_RESOURCE_ITEM, function(args)
        self:refreshItem();
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyResource", event.FOCUS_CHANGED, function(para)
         if para["get"] == "UISkyResource" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM, TOPMENU_FRAME_HEAD_AIRSHIP);
         elseif para["lose"] == "UISkyResource" then
             local btNode = findChildByName(self.node, "BT");
             btNode:setVisible(false);
         end
     end);

end

-- 注册点击事件
function UISkyResource:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyResource");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册天空商店点击事件
    local btnHonour = findChildByName(self.node, "BT/btn_info");
    btnHonour:setVisible(false);

    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);
end

function UISkyResource:refreshItem()
    self:initData();
    self:initGrids();
    self:redraw();
end
